<template>
  <div class="design-area" style="width: 100%; height: 100%; overflow: auto; background-color: #f0f0f0;">
    <div class="canvas-container" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" @drop="drop"
      @dragover="allowDrop" @mousedown="startSelection" @mousemove="updateSelection" @mouseup="endSelection">
      <svg class="canvas" :width="canvasWidth" :height="canvasHeight">
        <!--框选区域-->
        <rect v-if="isSelecting" class="selection-box" :x="selectionBox.x" :y="selectionBox.y"
          :width="selectionBox.width" :height="selectionBox.height" />
        <!-- 动态渲染控件 -->
        <g v-for="(control, index) in controls" :key="index" @click="selectControl(control, $event)"
          @mousedown="startDrag(control, $event)">
          <foreignObject v-if="control.type === 'text'" :x="control.x" :y="control.y" :width="control.width" :height="control.height">
            <div xmlns="http://www.w3.org/1999/xhtml" class="control-content"
              :class="{ selected: selectedControls.includes(control) }">
              {{ control.text }}
              <template v-if="selectedControls.includes(control)">
                <div class="resize-handle top-left" @mousedown.stop="startResize($event, 'top-left')"></div>
                <div class="resize-handle top-right" @mousedown.stop="startResize($event, 'top-right')"></div>
                <div class="resize-handle bottom-left" @mousedown.stop="startResize($event, 'bottom-left')"></div>
                <div class="resize-handle bottom-right" @mousedown.stop="startResize($event, 'bottom-right')"></div>
              </template>
            </div>
          </foreignObject>
        </g>
      </svg>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const emit = defineEmits(['control-selected']);

const props = defineProps({
  paperSize: {
    type: Object,
    required: true
  },
  isLandscape: {
    type: Boolean,
    default: false
  }
});

const mmToPx = (mm) => {
  // 默认使用 96 DPI（1英寸 = 25.4mm，96px / 25.4mm ≈ 3.78px/mm）
  const defaultDpi = 96;
  const pxPerMm = defaultDpi / 25.4;
  return mm * pxPerMm;
};
const canvasWidth = ref(mmToPx(props.paperSize.width));
const canvasHeight = ref(mmToPx(props.paperSize.height));
const controls = ref([]);
const selectedControls = ref([]);
const isSelecting = ref(false);
const isDragging = ref(false);
const selectionBox = ref({
  x: 0,
  y: 0,
  width: 0,
  height: 0
});

const startResize = (event, direction) => {

  // 阻止事件冒泡和默认行为
  event.stopPropagation();
  event.preventDefault();

  isDragging.value = true;

  const startX = event.clientX;
  const startY = event.clientY;
  const MIN_SIZE = 10; // 最小宽度和高度

  // 保存所有选中控件的初始尺寸和位置
  const initialStates = selectedControls.value.map(c => ({
    width: c.width,
    height: c.height,
    x: c.x,
    y: c.y
  }));

  const handleMouseMove = (e) => {
    const deltaX = e.clientX - startX;
    const deltaY = e.clientY - startY;

    selectedControls.value.forEach((c, index) => {
      switch (direction) {
        case 'top-left':
          c.width = Math.max(MIN_SIZE, initialStates[index].width - deltaX);
          c.height = Math.max(MIN_SIZE, initialStates[index].height - deltaY);
          c.x = initialStates[index].x + (initialStates[index].width - c.width);
          c.y = initialStates[index].y + (initialStates[index].height - c.height);
          break;
        case 'top-right':
          c.width = Math.max(MIN_SIZE, initialStates[index].width + deltaX);
          c.height = Math.max(MIN_SIZE, initialStates[index].height - deltaY);
          c.y = initialStates[index].y + (initialStates[index].height - c.height);
          break;
        case 'bottom-left':
          c.width = Math.max(MIN_SIZE, initialStates[index].width - deltaX);
          c.height = Math.max(MIN_SIZE, initialStates[index].height + deltaY);
          c.x = initialStates[index].x + (initialStates[index].width - c.width);
          break;
        case 'bottom-right':
          c.width = Math.max(MIN_SIZE, initialStates[index].width + deltaX);
          c.height = Math.max(MIN_SIZE, initialStates[index].height + deltaY);
          break;
      }
    });
  };

  const handleMouseUp = () => {
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
    setTimeout(() => isDragging.value = false, 100);
  };

  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};

//控件被选中
const selectControl = (control, event) => {
  if (isDragging.value) {
    return; // 如果是拖动操作则跳过选择逻辑
  }
  //按住Ctrl或Shift键的时候是多选，否则单选
  if (event.shiftKey || event.ctrlKey) {
    if (!selectedControls.value.includes(control)) {
      selectedControls.value.push(control);
    } else {
      selectedControls.value = selectedControls.value.filter(c => c !== control);
    }
  } else {
    selectedControls.value = [control];
  }
  emit('control-selected', selectedControls.value.length === 1 ? selectedControls.value[0] : null);
};


//更新画布大小
const updateCanvasSize = () => {
  const container = document.querySelector('.canvas-container');
  if (container) {
    container.style.setProperty('--canvas-width', `${canvasWidth.value}px`);
    container.style.setProperty('--canvas-height', `${canvasHeight.value}px`);
  }
};

watch(() => props.paperSize, (newSize) => {
  console.log('paperSize changed:', newSize);
  canvasWidth.value = mmToPx(props.isLandscape ? newSize.width : newSize.height);
  canvasHeight.value = mmToPx(props.isLandscape ? newSize.height : newSize.width);
  console.log('canvasWidth:', canvasWidth.value, 'canvasHeight:', canvasHeight.value);
  updateCanvasSize();
}, { immediate: true });

watch(() => props.isLandscape, (isLandscape) => {
  console.log('isLandscape changed:', isLandscape);
  canvasWidth.value = mmToPx(isLandscape ? props.paperSize.width : props.paperSize.height);
  canvasHeight.value = mmToPx(isLandscape ? props.paperSize.height : props.paperSize.width);
  console.log('canvasWidth:', canvasWidth.value, 'canvasHeight:', canvasHeight.value);
  updateCanvasSize();
});



const allowDrop = (event) => {
  event.preventDefault();
};


//拖拽上来一个控件，新建控件并选中
const drop = (event) => {
  event.preventDefault();
  const data = JSON.parse(event.dataTransfer.getData('text/plain'));
  const rect = event.currentTarget.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;

  console.log('Dropped control:', data);

  let createControl = {
    ...data,
    x,
    y,
    width: 100,
    height: 50
  };
  controls.value.push(createControl);
  selectControl(createControl, event);
};

//拖动控件位置
const startDrag = (control, event) => {
  if (isSelecting.value) return;
  if (!selectedControls.value.includes(control)) {
    return;
  }

  // 阻止事件冒泡和默认行为
  event.stopPropagation();
  event.preventDefault();

  isDragging.value = true;

  const currentSelection = [...selectedControls.value];
  const startX = event.clientX;
  const startY = event.clientY;
  const initialPositions = currentSelection.map(c => ({
    x: c.x,
    y: c.y
  }));

  const handleMouseMove = (moveEvent) => {
    const dx = moveEvent.clientX - startX;
    const dy = moveEvent.clientY - startY;
    currentSelection.forEach((c, index) => {
      c.x = initialPositions[index].x + dx;
      c.y = initialPositions[index].y + dy;
    });
  };

  const handleMouseUp = () => {
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
    // 延迟重置拖动状态，避免触发 click 事件
    setTimeout(() => isDragging.value = false, 100);
  };
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp, { once: true });
};

//开始框选
const startSelection = (event) => {
  console.log('Mouse down event triggered at:', event.clientX, event.clientY);

  // 获取点击位置相对于容器的坐标
  const rect = event.currentTarget.getBoundingClientRect();
  const clickX = event.clientX - rect.left;
  const clickY = event.clientY - rect.top;

  // 检查是否点击了任何控件
  const isClickOnControl = controls.value.some(control => {
    return (
      clickX >= control.x &&
      clickX <= control.x + control.width &&
      clickY >= control.y &&
      clickY <= control.y + control.height
    );
  });

  if (isClickOnControl) {
    console.log('Clicked on control area, skipping selection');
    return;
  }

  isSelecting.value = true;
  selectionBox.value = {
    x: clickX,
    y: clickY,
    width: 0,
    height: 0
  };
  console.log('Blank area clicked, selection started at:', selectionBox.value);
};

//更新框选范围
const updateSelection = (event) => {
  if (!isSelecting.value) {
    return;
  }
  const rect = event.currentTarget.getBoundingClientRect();
  selectionBox.value.width = event.clientX - rect.left - selectionBox.value.x;
  selectionBox.value.height = event.clientY - rect.top - selectionBox.value.y;
  console.log('Selection box updated:', selectionBox.value);
};

//结束框选，框中的控件全部选中
const endSelection = (event) => {
  console.log('Mouse up event triggered');
  if (!isSelecting.value) {
    console.log('Not in selection mode, skipping end');
    return;
  }
  isSelecting.value = false;
  const box = selectionBox.value;
  const normalizedBox = {
    x: box.width < 0 ? box.x + box.width : box.x,
    y: box.height < 0 ? box.y + box.height : box.y,
    width: Math.abs(box.width),
    height: Math.abs(box.height)
  };

  selectedControls.value = controls.value.filter(control => {
    return (
      control.x + control.width >= normalizedBox.x &&
      control.x <= normalizedBox.x + normalizedBox.width &&
      control.y + control.height >= normalizedBox.y &&
      control.y <= normalizedBox.y + normalizedBox.height
    );
  });
  console.log('Final selected controls:', selectedControls.value);
  emit('control-selected', selectedControls.value.length === 1 ? selectedControls.value[0] : null);
};
</script>

<style scoped>
.resize-handle {
  position: absolute;
  width: 8px;
  height: 8px;
  background-color: #1890ff;
  border-radius: 50%;
  cursor: nwse-resize;
}

.resize-handle.top-left {
  top: -4px;
  left: -4px;
  cursor: nwse-resize;
}

.resize-handle.top-right {
  top: -4px;
  right: -4px;
  cursor: nesw-resize;
}

.resize-handle.bottom-left {
  bottom: -4px;
  left: -4px;
  cursor: nesw-resize;
}

.resize-handle.bottom-right {
  bottom: -4px;
  right: -4px;
  cursor: nwse-resize;
}

.design-area {
  flex: 1;
  position: relative;
  overflow: auto;
  background-color: #f0f2f5;
  display: flex;
  justify-content: center;
  align-items: center;
}


.canvas-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  user-select: none;
}

.canvas {
  background-color: white;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  user-select: none;
}

.selection-box {
  fill: rgba(0, 123, 255, 0.2);
  stroke: rgba(0, 123, 255, 0.8);
  stroke-width: 1;
  pointer-events: none;
}


.control-content {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  word-break: break-all;
  overflow: hidden;
  border: 1px dashed #ccc;
  cursor: pointer;
}

.control-content.selected {
  border: 1px solid #1890ff;
  cursor: move;
}
</style>